package com.tous.translate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class GoogleTranslate {
	public static String translate(String sl, String tl, String text)
			throws IOException {
		// fetch
		URL url = new URL(
				"http://translate.google.com.tw/translate_a/t?client=t&hl=en&sl="
						+ sl
						+ "&tl="
						+ tl
						+ "&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q="
						+ URLEncoder.encode(text, "UTF-8"));
		URLConnection urlConnection = url.openConnection();
		urlConnection.setRequestProperty("User-Agent", "Something Else");
		BufferedReader br = new BufferedReader(new InputStreamReader(
				urlConnection.getInputStream()));
		String result = br.readLine();
		br.close();
		//System.out.println("Result is: " + result);
		result = result.substring(2, result.indexOf("]]") + 1);
		StringBuilder sb = new StringBuilder();

		//System.out.println("Result is: " + result);
		String[] splits = result.split("(?<!\\\\)\"");
		for (int i = 1; i < splits.length; i += 8)
			sb.append(splits[i]);
		return sb.toString().replace("\\n", "\n").replaceAll("\\\\(.)", "$1");
	}

	public static void main(String[] args) throws IOException {
		String sl = "en";
		String tl1 = "ca";
		String tl2 = "de";
		String text = "About 100 climate protesters arrested in march on Wall Street";
		
		
		System.out.println(text);
		System.out.println(translate(tl1,sl,translate(sl,tl1,text)));
		System.out.println(translate(tl2,sl,translate(sl,tl2,text)));
		
		
	}
}
